package com.cch.controller;

import com.cch.security.PhoneNumAuthenticationToken;
import com.cch.util.TokenUtil;
import jakarta.annotation.Resource;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


/**
 * @author cch
 * @date 2025年05月21日 12:39
 */
@RestController
public class LoginController {


    @Resource
    private AuthenticationManager authenticationManager;



    @PostMapping("/login/login")
    public String login(@RequestBody Map map) {
        //通过AuthenticationManager的authenticate方法来进行用户认证
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(map.get("username"), map.get("password"));
        Authentication authenticate = authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if (authenticate == null) {
            return "登录校验失败";
        }
        String token = TokenUtil.genAccessToken(map.get("username").toString(),"admin","123");
        return token;
    }

    @PostMapping("/login/phone")
    public String loginByPhoneAndCode(@RequestBody Map map) {
        //security已经错过校验, 这里不再校验验证码
        //进行手动security登陆
        PhoneNumAuthenticationToken phoneNumAuthenticationToken = new PhoneNumAuthenticationToken(map.get("mobile").toString());
        Authentication authenticate = authenticationManager.authenticate(phoneNumAuthenticationToken);

        if (authenticate == null) {
            return "登录校验失败";
        }
        String token = TokenUtil.genAccessToken(map.get("mobile").toString(),"admin","123");
        return token;
    }



}
